package _interview75;

import _object.TreeNode;

/**
 * 450. 删除二叉搜索树中的节点
 */
public class No450 {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) return null;
        int curVal = root.val;
        if (curVal > key) root.left = deleteNode(root.left, key);
        else if (curVal < key) root.right = deleteNode(root.right, key);
        else {
            if (root.left == null) return root.right;
            else if (root.right == null) return root.left;
            else {
                TreeNode leftNode = root.left;
                while (leftNode.right != null) leftNode = leftNode.right;
                leftNode.right = root.right;
                return root.left;
            }
        }
        return root;
    }
}
